// $.ajax({
//     url: `https://ds.suning.com/ds/his/new/-${text}-0-1_0-autoComplateCallback_184b31b125a59d8c382d3d8382d23350.jsonp?callback=autoComplateCallback_184b31b125a59d8c382d3d8382d23350&_=1639181419932`,
//     dataType: 'jsonp',
//     jsonp: 'cb',
//     jsonpCallback: 'searchHotkeywords',
//     success (res){
//         console.log(res)
//     }
// })


// 顶部链接
// https://lib.suning.com/api/jsonp/cb/headToolbar-headToolbar.jsonp?callback=headToolbar&_=1639213912398
// 点击跳转支购物车
$('.gwc').click(function () {
  window.location.href = './cart.html'
})

// 登录信息
const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')
const onBox = $('ul>.on')
const offBox = $('ul>.off')
if (!id) {
  offBox.removeClass('active')
  onBox.addClass('active')
}
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8888/users/info?id=' + id)
xhr.onload = function () {
  const res = JSON.parse(xhr.responseText)
  if (res.code === 401) {
    onBox.addClass('active')
    offBox.removeClass('active')
  }
  if (res.code === 1) {
    $('ul>.on:first').html(res.info.nickname)
    offBox.addClass('active')
    onBox.removeClass('active')
  }
}
xhr.setRequestHeader('authorization', token)
xhr.send()
const inp = document.querySelector('form > .hq')
const ulBox = document.querySelector('form > ul')
inp.oninput = function () {
  const text = inp.value.trim()
  const script = document.createElement('script')
  script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=31660,26350&wd=${text}&req=2&csor=1&cb=handler&_=1639190662005`
  document.body.appendChild(script)
  script.remove()
}
function handler(res) {
  if (!res.g) {
    ulBox.style.display = 'none'
    return
  }
  let str = ''
  res.g.forEach(item => {
    str += `
        <li>${item.q}</li>
      `
  })
  ulBox.innerHTML = str
  ulBox.style.display = 'block'
}
//注销
const logoutBtn = $('li>.logout')
logoutBtn.click(async () => {
  const res = $.ajax({
    url: 'http://localhost:8888/users/logout',
    data: { id },
    dataType: 'json'
  })
  console.log(res.code);
  if (res.code === 1) {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('token')
  }
  window.location.reload()
})

// 轮播图
const banner = document.querySelector('.banner')
const imgBox = document.querySelector('.imgBox')
const pointBox = document.querySelector('.pointBox')
let banner_width = banner.clientWidth
let index = 1
let timer = 0
let flag = true
copyEle()
function copyEle() {
  const first = imgBox.firstElementChild.cloneNode(true)
  const last = imgBox.lastElementChild.cloneNode(true)
  imgBox.appendChild(first)
  imgBox.insertBefore(last, imgBox.firstElementChild)
  imgBox.style.width = imgBox.children.length * 100 + '%'
  imgBox.style.left = -banner_width + 'px'
}
setPoint()
function setPoint() {
  const pointNum = imgBox.children.length - 2
  for (var i = 0; i < pointNum; i++) {
    const li = document.createElement('li')
    if (i === 0) li.className = 'active'
    li.classList.add('item')
    li.dataset.point = i
    pointBox.appendChild(li)
  }
}
autoPlay()
function autoPlay() {
  timer = setInterval(() => {
    index++
    move(imgBox, { left: -index * banner_width }, moveEnd)
  }, 3500)
}
moveEnd()
function moveEnd() {
  if (index === imgBox.children.length - 1) {
    index = 1
    imgBox.style.left = -index * banner_width + 'px'
  }
  if (index === 0) {
    index = imgBox.children.length - 2
    imgBox.style.left = -index * banner_width + 'px'
  }
  for (let i = 0; i < pointBox.children.length; i++) {
    pointBox.children[i].classList.remove('active')
  }
  pointBox.children[index - 1].classList.add('active')
  flag = true
}
overOut()
function overOut() {
  banner.addEventListener('mouseover', () => clearInterval(timer))
  banner.addEventListener('mouseout', () => autoPlay())
}
bindEvent()
function bindEvent() {
  banner.addEventListener('click', e => {
    if (e.target.className === 'left') {
      if (flag === false) return
      flag = false
      index--
      move(imgBox, { left: -index * banner_width }, moveEnd)
    }
    if (e.target.className === 'right') {
      if (flag === false) return
      flag = false
      index++
      move(imgBox, { left: -index * banner_width }, moveEnd)
    }
    if (e.target.className === 'item') {
      if (flag === false) return
      flag = false
      index = e.target.dataset.point - 0 + 1
      move(imgBox, { left: -index * banner_width }, moveEnd)
    }
  })
}
changeTab()
function changeTab() {
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') clearInterval(timer)
    if (document.visibilityState === 'visible') autoPlay()
  })
}


// 二级菜单
const listBox = document.querySelector('.b > .b1 > .list')
const contentBox = document.querySelector('.b > .b1 > .content')
// 渲染页面
bindHtml()
function bindHtml() {
  // 利用 list 数组渲染页面
  let str = ''
  list.forEach(item => {
    str += `
      <li data-id="${item.id}">
    `
    // item.name 是一个数组, 有多少项就有多少个 span
    item.name.forEach((t, i) => {
      str += `
        <span>${t.title}</span>
        ${i === item.name.length - 1 ? '' : '<i>/</i>'}
      `
    })
    str += `
      </li>
    `
  })
  listBox.innerHTML = str
}
// 绑定事件
const lis = listBox.querySelectorAll('.b1 li')
lis.forEach(function (item) {
  item.onmouseover = function () {
    const id = item.dataset.id
    // 从数组中找到 id 对应的数据
    const data = list.find(item => item.id === id)
    bindRightHtml(data)
    // 使用 data 把右边的数据渲染完毕即可
    contentBox.classList.add('active')
  }
})
listBox.onmouseleave = function () {
  contentBox.classList.remove('active')
}
// 渲染右边的函数
function bindRightHtml(data) {
  let str = `
    <div class="left">
      <ul class="tags">
  `
  data.tags.forEach(item => {
    str += `
      <li>
        <span>${item.title}</span>
        <i class="icon">&gt;</i>
      </li>
    `
  })
  str += `
      </ul>
      <ul class="cate_list">
  `
  data.children.forEach(item => {
    str += `
      <li>
        <div class="name">
          <span>${item.title}</span>
          <i>&gt;</i>
        </div>
        <ol>
    `
    item.children.forEach(t => {
      str += `
        <li>${t.title}</li>
      `
    })
    str += `
        </ol>
      </li>
    `
  })
  str += `
      </ul>
    </div>
    <div class="right">
      <ul class="small_list">
  `
  data.smallPics.slice(0, 8).forEach(item => {
    str += `
      <li>
        <img src="${item.url}" alt="">
      </li>
    `
  })
  str += `
      </ul>
      <ul class="big_list">
  `
  data.bigPics.slice(0, 2).forEach(item => {
    str += `
      <li>
        <img src="${item.url}" alt="">
      </li>
    `
  })
  str += `
      </ul>
    </div>
  `
  contentBox.innerHTML = str
}


//右侧导航栏
$('.sn i').on({
  mouseover() {
    $(this).nextAll().addClass('active').fadeIn(100)
    // $(this).nextAll('.b').addClass('active').fadeIn(100)
  },
  mouseout() {
    $(this).nextAll().removeClass('active').fadeOut(100)
  },
})


// 推荐榜单
$.ajax({
  url: `https://tuijian.suning.com/recommend-portal/dyBase.jsonp`,
  data: {
    u: '',
    c: '163909370247761256',
    cityId: '010',
    sceneIds: '31-42',
    count: 9,
    num: 3,
    parameter: 66601,
    storeCode: '',
    merchantCode: '',
    channelType: '',
    delivery: '',
    sceneCode: '',
    snTerminal: '284000002001'
  },
  dataType: 'jsonp',
  success(res) {
    const aaa = []
    res.sugGoods[0].list.forEach(item => {
      if (!item.list) aaa.push(item)
      else item.list.forEach(t => aaa.push(t))
    })
    let str = ''
    aaa.forEach(item => {
      str += `
        <li>
            <div class="label">
                <img src="	https://image4.suning.cn/uimg/cms/img/159533153596347678.png" alt="">
                <p>人气榜</p>
            </div>
            <img class="main-pic" src="${item['skus'][0].pictureUrl}">
            <p class="name">${item.labelName}</p>
            <p class="desc">
            <img class="icon" src="//image5.suning.cn/uimg/cms/img/159525756682624771.png">
            <span>${item.multiDepiction}</span>
            </p>
        </li>
      `
    })
    $('.d > .content-box > ul').html(str)
  }
})

//为你推荐
$.ajax({
  url: `https://f.m.suning.com/api/getPcIndexProTag.do`,
  data: {
    u: '',
    c: '163909370247761256',
    cityCode: '010',
    districtCode: '0100100',
    sceneIds: '12-14',
    sceneIds2: '12-14',
    count: 100,
    count2: 4,
    flag: 1,
    channel: 322,
    terminal: 'pc',
    snTerminal: '284000002001',
  },
  dataType: 'jsonp',
  success(res) {
    str = ``
    res.data.sugGoods[0].skus.forEach(item => {
      str += `
        <li>
            <img src="${item.pictureUrl}">
            <p class="title"><i class="zyIcon"></i>${item.sugGoodsName}</p>
            <p class="price-box"><span class="price"><i>¥</i><em>${item.price}</em></span><span class="refprice"><i>¥</i><em>${item.snPrice}</em></span></p>
            <p class="cxIcon"></p>
        </li>
        `
    })
    $('.f').html(str)
  }
})


// 返回顶部
$(window).scroll(function () {
  if ($(window).scrollTop() > 300) {
    $('.fnhui').fadeIn(1000)
  } else {
    $('.fnhui').fadeOut(1000)
  }
})
$('.fnhui').click(function () {
  $('html,body').animate({
    scrollTop: 0
  }, 1000)
})


//楼层导航
$('.lcdh > li').click(function () {
  const index = $(this).index()
  const span = $('.lc').eq(index)
  console.log(index, span);
  $('html, body').animate({ scrollTop: span.offset().top }, 500)
})
//滚动事件
$(window).scroll(() => {
  $('.lc').each(function (index, item) {
    if ($(window).scrollTop() <= 300) {
      $('.lcdh').fadeOut(1000)
    } else {
      $('.lcdh').fadeIn(1000)
    }
    if ($(window).scrollTop() >= $(item).offset().top) {
      $('.lcdh > li').eq(index).addClass('active').siblings().removeClass('active')
    } else {
      $('.lcdh > li').eq(index).removeClass('active')
    }
  })
})